<script setup>
import {ref, reactive, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import axios from 'axios'
import {Plus} from "@element-plus/icons-vue";
import {getAuthHeaders} from '@/utils.js'

import {ElConfigProvider} from 'element-plus';
import zhCn from 'element-plus/es/locale/lang/zh-cn';

// 分页与数据
const employeeList = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const loading = ref(false)

// 新增/编辑弹窗
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()
const form = reactive({
  accountId: undefined,
  accountName: '',
  password: '',
  phone: '',
  address: '',
  avatarUrl: '',
  alipayCount: '',
  basicSalary: '',
  perHourFee: ''
})

// 上传相关
const uploadUrl = '/carRepair/upload/file'
const uploadHeaders = getAuthHeaders
const handleAvatarSuccess = (res) => {
  console.log(res)
  if (res.code === 200) {
    form.avatarUrl = res.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error('上传失败')
  }
}

const beforeUpload = (file) => {
  const isImg = file.type.startsWith('image/')
  if (!isImg) {
    ElMessage.error('只能上传图片文件!')
  }
  return isImg
}

// 查询员工
const fetchEmployees = async () => {
  loading.value = true
  try {
    const {data} = await axios.get('/carRepair/admin/accountManage/employee', {
      params: {pageNum: pageNum.value, pageSize: pageSize.value}
    })
    if (data.code === 200) {
      employeeList.value = data.data.records
      total.value = data.data.total
    }
  } finally {
    loading.value = false
  }
}

// 打开新增/编辑弹窗
const openDialog = (row = null) => {
  if (row) {
    isEdit.value = true
    Object.assign(form, row)
  } else {
    isEdit.value = false
    Object.assign(form, {
      accountId: undefined,
      accountName: '',
      password: '',
      phone: '',
      address: '',
      avatarUrl: '',
      alipayCount: '',
      basicSalary: '',
      perHourFee: ''
    })
  }
  dialogVisible.value = true
}

// 新增/编辑保存
const handleSave = async () => {
  await formRef.value.validate()
  const payload = {...form}
  if (isEdit.value) {
    await axios.put('/carRepair/admin/accountManage/employee', payload)
    ElMessage.success('修改成功')
  } else {
    await axios.post('/carRepair/admin/accountManage/employee', payload)
    ElMessage.success('新增成功')
  }
  dialogVisible.value = false
  fetchEmployees()
}

// 删除员工
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该员工吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    ElMessageBox.confirm('请再次确认是否删除该员工？', '二次确认', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'error',
    }).then(async () => {
      await axios.delete(`/carRepair/admin/accountManage/employee/${row.accountId}`)
      ElMessage.success('删除成功')
      fetchEmployees()
    })
  })
}

onMounted(() => {
  fetchEmployees()
})
</script>

<template>
  <div class="employee-manage">
    <!-- 新增员工 -->
    <el-button type="primary" @click="openDialog()" style="margin-bottom: 16px">新增员工</el-button>
    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="isEdit ? '编辑员工' : '新增员工'" v-model="dialogVisible" width="500px">
      <el-form :model="form" ref="formRef" label-width="100px" :rules="{
        accountName: [{ required: true, message: '请输入员工名称', trigger: 'blur' }],
        password: [{ required: true, message: '请输入员工密码', trigger: 'blur' }],
        phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
        address: [{ required: true, message: '请输入住址', trigger: 'blur' }],
        avatarUrl: [{ required: true, message: '请上传头像', trigger: 'change' }],
        alipayCount: [{ required: true, message: '请输入支付宝账号', trigger: 'blur' }],
        basicSalary: [{ required: true, message: '请输入基本工资', trigger: 'blur' }],
        perHourFee: [{ required: true, message: '请输入工时费', trigger: 'blur' }],
      }">
        <el-form-item label="头像" prop="avatarUrl">
          <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeUpload"
              :headers="uploadHeaders()"
          >
            <img v-if="form.avatarUrl" :src="form.avatarUrl" class="avatar" alt=""/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="员工名称" prop="accountName">
          <el-input v-model="form.accountName" placeholder="请输入账户名称"/>
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入员工登录密码"/>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话"/>
        </el-form-item>
        <el-form-item label="住址" prop="address">
          <el-input v-model="form.address" placeholder="请输入住址"/>
        </el-form-item>
        <el-form-item label="支付宝账号" prop="alipayCount">
          <el-input v-model="form.alipayCount" placeholder="请输入支付宝账号"/>
        </el-form-item>
        <el-form-item label="基本工资" prop="basicSalary">
          <el-input v-model="form.basicSalary" placeholder="请输入基本工资" type="number"/>
        </el-form-item>
        <el-form-item label="工时费" prop="perHourFee">
          <el-input v-model="form.perHourFee" placeholder="请输入工时费" type="number"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>

    <!-- 员工表格 -->
    <el-table :data="employeeList" border stripe v-loading="loading" style="width: 100%">
      <el-table-column label="头像" min-width="100">
        <template #default="scope">
          <img :src="scope.row.avatarUrl" alt="头像" style="width:40px;height:40px;border-radius:50%"/>
        </template>
      </el-table-column>
      <el-table-column prop="accountName" label="账户名称" min-width="120"/>
      <el-table-column prop="phone" label="联系电话" min-width="120"/>
      <el-table-column prop="address" label="住址" min-width="120"/>
      <el-table-column prop="alipayCount" label="支付宝账号" min-width="120"/>
      <el-table-column prop="basicSalary" label="基本工资" min-width="100"/>
      <el-table-column prop="perHourFee" label="工时费" min-width="100"/>
      <el-table-column label="操作" min-width="140">
        <template #default="scope">
          <el-button size="small" @click="openDialog(scope.row)">修改</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 16px 0; text-align: right">
      <el-config-provider :locale="zhCn">
        <el-pagination
            background
            layout="total, prev, pager, next, jumper, sizes"
            :total="total"
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            @current-change="fetchEmployees"
            @size-change="fetchEmployees"
            :page-sizes="[10, 20, 50, 100]"
            :hide-on-single-page="false"
        />
      </el-config-provider>
    </div>
  </div>
</template>

<style scoped>
.employee-manage {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
}

.avatar-uploader .avatar {
  width: 60px;
  height: 60px;
  display: block;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #eee;
}

.avatar-uploader-icon {
  font-size: 32px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  line-height: 60px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
}
</style>